package com.nnfe.fyd.http;

import com.nnfe.fyd.App;
import com.nnfe.fyd.bean.HttpResult;
import com.nnfe.fyd.utils.LogUtil;
import com.nnfe.fyd.utils.NetworkUtil;
import com.nnfe.fyd.utils.ToastUtil;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by Administrator on 2016/12/29.
 */

public abstract class CallbackImpl<T> implements Callback<HttpResult<T>> {
    @Override
    public void onResponse(Call<HttpResult<T>> call, Response<HttpResult<T>> response) {

        if (response.isSuccessful()) {
            onRequestFinish();
            if (response.body() == null) {
                ToastUtil.showToast("未知错误");
                return;
            }
            if (response.body() != null && response.body().getStatus() == 1) {
                ToastUtil.showToast(response.body().getMsg());
                return;
            }
            // status = 9000 token 无效
            if (response.body() != null && response.body().getStatus() == 9000) {
                ToastUtil.showToast("登录信息过期，请重新登录");
                // 重新登录操作
                return;
            }

            responseSuccess(call, response);
        } else {
            onRequestFinish();
            ToastUtil.showToast("服务器错误或网络异常");
            return;
        }

    }


    @Override
    public void onFailure(Call<HttpResult<T>> call, Throwable t) {
        onRequestFinish();
        if (!NetworkUtil.isNetworkAvailable(App.getContext())) {
            ToastUtil.showToast("无网络连接，请检查网络后重试");
            return;
        }
        if (t.toString().equals("java.net.SocketTimeoutException")
                || t.toString().equals("java.net.ConnectTimeoutException")||t.toString().contains("ETIMEDOUT")) {
            ToastUtil.showToast("请求超时，请重试");
            return;
        }
        if (t.toString().contains("ConnectException")) {
            ToastUtil.showToast("网络连接错误，请检查网络。");
            return;
        }
        if (t.toString().contains("com.google.gson.JsonSyntaxException")) {
            ToastUtil.showToast("数据解析错误");
            LogUtil.e("dada",t.toString());
            return;
        }
    }

    /**
     * 请求结束(不关注是否请求成功)后执行的操作, 如： 取消刷新，  取消dialog 等等,  非必须
     */
    protected void onRequestFinish() {
    }

    /**
     * 无异常的请求成功
     *
     * @param call
     * @param response
     */
    public abstract void responseSuccess(Call<HttpResult<T>> call, Response<HttpResult<T>> response);


}
